package Offer;

/**
 * 重建二叉树
 *
 * @author 是阿秋啊
 * @date 2022/04/18 20:12
 **/
public class Num07 {
    private int index = 0;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return getNode(preorder, inorder, 0, inorder.length - 1);
    }

    private TreeNode getNode(int[] preorder, int[] inorder, int l, int r) {
        if (l > r) {
            return null;
        }
        if (index == preorder.length) {
            return null;
        }
        TreeNode root = new TreeNode(preorder[index]);
        index++;
        int mid = find(inorder, root.val);
        root.left = getNode(preorder, inorder, l, mid - 1);
        root.right = getNode(preorder, inorder, mid + 1, r);
        return root;
    }

    private int find(int[] inorder, int val) {
        for (int i = 0; i < inorder.length; i++) {
            if (inorder[i] == val) {
                return i;
            }
        }
        return -1;
    }
}
